<?php

namespace Frieza\Modules\McnUser\Controllers;

use App\Http\Controllers\Controller;
use Doraemon\model\McnUser;
use Doraemon\model\McnUserExtendInfo;
use Doraemon\model\McnUserProfession;
use Doraemon\model\Member as mMember;
use Doraemon\service\Creator\UserLevel3;
use Doraemon\service\Right\UserRightNew;
use Doraemon\tools\Creator\GrowthConfig;
use Doraemon\tools\Log;
use Encore\Admin\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

class McnUserDetailController extends Controller
{

    public function index(Request $request, Content $content, $iUid)
    {
        Admin::script(<<<EOF
/*
 * @Author: 陈雪勇
 * @Date: 2022-05-19 11:06:26
 * @LastEditors: 陈雪勇
 * @LastEditTime: 2022-05-23 12:02:58
 * @Description:
 */
$(function () {
  function pageInit() {
    $(".nav-tabs > li:first-child").addClass("active");
    $(".dimension-1").show();
  }

  $(document).ready(() => {
    console.log(123);
    pageInit();
    
    setTimeout(() => {
      if ($('.selectpicker').length) {
        $('.selectpicker').selectpicker('render'); // 页面加载时手动初始化 bootstrap-select
      }
    }, 1000)
  })

  function formatSelector(id) {
    const selector = `#` + id;
    const editSelector = selector + `_wrapper > .glyphicon-edit`;
    const okSelector = selector + `_wrapper > .glyphicon-ok`;
    const removeSelector = selector + `_wrapper > .glyphicon-remove`;

    return [selector, editSelector, okSelector, removeSelector];
  }

  const lastValObj = {};
  function toggleEdit(id = "house_style", isEdit = true, isCancel = false) {
    const [selector, editSelector, okSelector, removeSelector] =
      formatSelector(id);
    const inputElem = $(selector);
    const editElem = $(editSelector);
    const okElem = $(okSelector);
    const removeElem = $(removeSelector);

    if (isEdit) {
      lastValObj[id] = inputElem.val(); // 进入编辑状态时记录当前的值
      inputElem.attr("disabled", false);
      editElem.hide();
      okElem.show();
      removeElem.show();
    } else {
      if (isCancel) {
        // 取消编辑的时候恢复值
        console.log(lastValObj);
        if (lastValObj[id] !== undefined) {
          inputElem.val(lastValObj[id]);
        }
      }

      inputElem.attr("disabled", true);
      editElem.show();
      okElem.hide();
      removeElem.hide();
    }
    
    if (id === 'user_profession' || id === 'occupation') {
      inputElem.selectpicker('refresh'); // select 组件的 disable 属性变化时，刷新以生效
    }
  }

  function syncHomeDesc(value) {
    ['1', '2', '3'].forEach(key => {
      $('#description_homeJsonSepstyle_' + key).val(value);
    })
  }

  function request(key, value) {
    const uid = $('#uid')[0].innerText;
    console.log('request: ', uid, key, value);

    if (!uid) {
      alert('需要登录');
      return;
    }
    const uri = `/admin/mcnUser/save/` + uid + '?' + key + '=' + encodeURIComponent(value);
    console.log(uri);
    $.get(uri, (data, status) => {
      console.log(data, status);
      
      // 如果操作 家的形容-风格 字段，则同步不同位置的值
      if (key.indexOf('description_homeJsonSepstyle') === 0) {
        syncHomeDesc(value);
      }
    })
  }
  
  function requestAll(data) {
    const uid = $('#uid')[0].innerText;
    console.log('request: ', uid);

    if (!uid) {
      alert('需要登录');
      return;
    }
    const queryString = Object.keys(data).map(key => key + '=' + encodeURIComponent(data[key])).join('&');
    const uri = `/admin/mcnUser/save/` + uid + '?' + queryString;
    console.log(uri);
    $.get(uri, (rdata, status) => {
      console.log(rdata, status, data);
      if (rdata == 'success') {
        alert('保存成功');
        
        // 用维度 9 的 风格 同步基本信息中和维度 4 中对应值
        syncHomeDesc(data.description_homeJsonSepstyle_3);
      } else {
        alert('保存失败');
      }
    })
  }

  const platforms = [
    "douyin", // 抖音
    "xiao_hong_shu", // 小红书
    "bilibili", // bilibili
    "weibo", // 微博
    "zhu_xiao_bang", // 住小邦
    "yi_dou_tang", // 一兜糖
    "guang_guang", // 逛逛
    "kuai_shou", // 快手
    "zhihu", // 知乎
    "other_platform", // 其他
  ];

  const editList = [
    "description_homeJsonSepstyle_1", // 用户基础信息 家的形容-风格
    "description_homeJsonSepstyle_2", // 维度4-房屋状况 家的形容-风格
    "user_profession", // 维度5-社会属性 职业
    "postal_address_1", // 维度5-社会属性 通讯地址1
    "postal_address_2", // 维度5-社会属性 通讯地址2
    "whether_commerce_cooper", // 维度6-商业合作 是否可商业合作
    "is_auth", // 维度6-商业合作 是否入淘
    "performance_capacity", // 维度6-商业合作 C-履约能力分值
    "fans_love_watch", // 维度6-商业合作 粉丝爱看
    "industry_influence", // 维度6-商业合作 行业影响力
    "bus_article_output", // 维度6-商业合作 商业图文产出能力
    "bus_video_output", // 维度6-商业合作 商业视频产出能力
    "express_ability", // 维度6-商业合作 表达能力
    "cooperation_match", // 维度6-商业合作 商业配合度
    "responsible_operation", // 维度7-运营 负责运营
    "community", // 维度7-运营 所在社群
    "operational_remarks", // 维度7-运营 运营备注
    // 维度8-站外平台链接及活跃情况
    ...platforms.reduce(
      (acc, cur) => [
        ...acc,
        ...["JsonSepnick", "JsonSepfans_num", "JsonSephome_page_links"].map((item) => cur + item),
      ],
      []
    ),
    "is_sign", // 维度10-是否签约
    "share_proportion", // 维度10-分成比例
    "red_book_img_text_price", // 维度10-小红书-图文笔记一口价
    "red_book_video_price", // 维度10-小红书-视频笔记一口价
    "guang_guang_img_text_price", // 维度10-逛逛-图文报价
    "guang_guang_60s_video_price", // 维度10-逛逛-60s视频报价
    "guang_guang_60s_120s_video_price", // 维度10-逛逛-60s-120s视频报价
    "is_super", // 维度10-是否为超级居住者
  ];
  console.log(editList);
  editList.map((editId) => {
    const [selector, editSelector, okSelector, removeSelector] =
      formatSelector(editId);
    $(editSelector).on("click", (e) => {
      toggleEdit(editId, true);
    });

    $(okSelector).on("click", (e) => {
      const value = $(selector).val();
      console.log(editId, value);
      // TODO: 修改数据接口调用
      toggleEdit(editId, false);

      request(editId, value);
    });

    $(removeSelector).on("click", (e) => {
      toggleEdit(editId, false, true);
    });
  });

  /**
   * 导航栏交互
   */
  $(".nav-tabs > li").on("click", (e) => {
    const { index } = e.currentTarget.dataset;
    console.log(e.currentTarget.dataset.index);
    $(".nav-tabs > li").removeClass("active");
    $(e.currentTarget).addClass("active");
    $(".dimension").hide();
    $(`.dimension-` + index).show();
  });

  $("#dimension9Save").on("click", (e) => {
    const formItems = $(".dimension-9 .item-value");
    const obj = {};
    [...Array.from(formItems)].forEach((item) => {
      obj[$(item).attr("id")] = $(item).val();
//      request($(item).attr("id"), $(item).val());
    });
    requestAll(obj);
    console.log(formItems, obj);
  });
});
EOF
        );
        Admin::style(<<<EOF
.margin-top-10 {
  margin-top: 10px;
}

.margin-top-30 {
  margin-top: 30px;
}

.form-select {
  width: 100%;
}

.container {
  padding-top: 15px;
  width: 100%;
  min-width: 970px;
}

.base-info {
  border-top: solid 1px #e5e5e5;
  display: flex;
}

.left {
  flex-shrink: 0;
  width: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  border: solid 1px #e5e5e5;
}

.home-page {
  cursor: pointer;
}

.right {
  flex: 1;
  padding: 10px 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.info-item {
  width: 30%;
  border-bottom: solid 1px #e5e5e5;
  margin-top: 12px;
  display: flex;
  align-items: center;
  word-break: break-all;
}

.info-item.no-margin {
  margin-top: 0;
}

.item-label {
  width: 132px;
  flex-shrink: 0;
}

.info-item.placeholder {
  border: none;
}

.info-item .glyphicon {
  margin-left: 10px;
  cursor: pointer;
}

input[disabled] {
  border: none;
  background: none !important;
  margin: 0;
  padding: 0;
  box-shadow: none;
}

.link[disabled] {
  cursor: pointer;
  color: #337ab7;
}

.link[disabled]:hover {
  text-decoration: underline;
}

.glyphicon-ok {
  color: green;
}

#description_homeJsonSepstyle_wrapper > .glyphicon-ok,
#house_style_1_wrapper > .glyphicon-ok {
  display: none;
}

#description_homeJsonSepstyle_wrapper > .glyphicon-remove,
#house_style_1_wrapper > .glyphicon-remove {
  display: none;
}

.glyphicon-ok,
.glyphicon-remove {
  display: none;
}

.nav-tabs {
  display: flex;
  overflow-x: auto;
}

.nav-tabs::-webkit-scrollbar {
  display: none;
}

.nav-tabs > li[role="presentation"] {
  white-space: nowrap;
}

.nav-tabs a {
  color: #666;
}

.nav-tabs .active a {
  background-color: #337ab7 !important;
  color: #fff !important;
}

.dimension {
  display: none;
  padding: 20px 0;
}

.info-item-wrapper {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.dimension-top {
  display: flex;
  justify-content: space-between;
}

.dimension-top > .part {
  width: 20%;
}

.dimension-top > .part > .info-item {
  width: auto;
}

.dimension-bottom {
  margin-top: 50px;
  display: flex;
  justify-content: space-between;
}

.dimension-bottom > .info-item {
  width: 20%;
}

.dimension-3 > .info-item,
.dimension-4 > .info-item,
.dimension-5 > .info-item,
.dimension-7 > .info-item {
  width: 50%;
}

.dimension-3 > .info-item > .item-label,
.dimension-4 > .info-item > .item-label,
.dimension-5 > .info-item > .item-label,
.dimension-7 > .info-item > .item-label {
  width: 180px;
}

.dimension-6 > .dimension-top > .part,
.dimension-8 > .dimension-top > .part {
  width: 28%;
}

.dimension-8 > .dimension-top > .part > .info-item > .item-label {
  width: 80px;
}

.dimension-6 > .dimension-top > .part .item-label {
  width: 150px;
}

.dimension-top.column-2 > .part {
  width: 45%;
}

.dimension-top.column-2 > .part .item-label {
  width: 150px;
}

.dimension-10 > .dimension-top.column-2 > .part .item-label {
  width: 165px;
}

button[type="submit"] {
  margin-top: 20px;
}
EOF
        );

        $aUser = mMember::getUser($iUid);
        $aMcnUser = McnUser::get('*', ["uid" => $iUid]);
        $aMcnUserExt = McnUserExtendInfo::get('*', ["uid" => $iUid]);
        $aProfession = [];
        if ($aMcnUserExt['user_profession']) {
            $aProfession = McnUserProfession::get('*', ['id' => $aMcnUserExt['user_profession']]);
        }
        $aProfessionAll = [];
        $aProfessionRow = McnUserProfession::select('*', [
            "ORDER" => [
                "pid" => "ASC",
                "id" => "ASC"
            ],
        ]);
        foreach ($aProfessionRow as $row) {
            if ($row['pid'] == 0) {//行业
                $row['subs'] = [];
                $aProfessionAll[$row['id']] = $row;
            } else {//职业
                $aProfessionAll[$row['pid']]['subs'][] = $row;
            }
        }

        Log::debug("mcn用户信息", [$aUser, $aMcnUser, $aMcnUserExt, $aProfession, $aProfessionAll]);

        //处理json字段数据
        $aMcnUser['note_num'] = json_decode($aMcnUser['note_num'], true);
        $aMcnUser['article_num'] = json_decode($aMcnUser['article_num'], true);
        $aMcnUser['video_num'] = json_decode($aMcnUser['video_num'], true);
        $aMcnUser['house_num'] = json_decode($aMcnUser['house_num'], true);
        $aMcnUser['business_content_soft'] = json_decode($aMcnUser['business_content_soft'], true);
        $aMcnUser['business_content_hard'] = json_decode($aMcnUser['business_content_hard'], true);
        $aMcnUserExt['human_description'] = json_decode($aMcnUserExt['human_description'], true);
        $aMcnUserExt['description_home'] = json_decode($aMcnUserExt['description_home'], true);

        $aMcnUserExt['zhu_xiao_bang'] = json_decode($aMcnUserExt['zhu_xiao_bang'], true);
        $aMcnUserExt['yi_dou_tang'] = json_decode($aMcnUserExt['yi_dou_tang'], true);
        $aMcnUserExt['guang_guang'] = json_decode($aMcnUserExt['guang_guang'], true);
        $aMcnUserExt['douyin'] = json_decode($aMcnUserExt['douyin'], true);
        $aMcnUserExt['weibo'] = json_decode($aMcnUserExt['weibo'], true);
        $aMcnUserExt['xiao_hong_shu'] = json_decode($aMcnUserExt['xiao_hong_shu'], true);
        $aMcnUserExt['bilibili'] = json_decode($aMcnUserExt['bilibili'], true);
        $aMcnUserExt['zhihu'] = json_decode($aMcnUserExt['zhihu'], true);
        $aMcnUserExt['kuai_shou'] = json_decode($aMcnUserExt['kuai_shou'], true);
        $aMcnUserExt['other_platform'] = json_decode($aMcnUserExt['other_platform'], true);

        $aMcnUserExt['postal_address'] = explode('|', $aMcnUserExt['postal_address']);

        //优质率
        $aMcnUser['note_num']['noteHighRate'] *= 100;
        $aMcnUser['article_num']['blankHighRate'] *= 100;
        $aMcnUser['video_num']['videoHighRate'] *= 100;
        $aMcnUser['house_num']['articleHighRate'] *= 100;

        //精选率
        $aMcnUser['note_num']['noteBestRate'] *= 100;
        $aMcnUser['article_num']['blankBestRate'] *= 100;
        $aMcnUser['video_num']['videoBestRate'] *= 100;
        $aMcnUser['house_num']['articleBestRate'] *= 100;

        $aUser['avatar_url'] = \Doraemon\service\Member::getAvatar($aUser['uid'], $aUser['avatar_version'], \Doraemon\tools\ImgUrl::IMAGE_SIZE_SQ_BIG);

        $levelInfo = UserLevel3::getLevelInfoByUid($aUser['uid']);
        $level = $levelInfo['user_level_name'];
        $aMcnUser['creator_level'] = $levelInfo['user_level'];
        if ($level == UserRightNew::USER_LEVEL3) {
            $aMcnUser['level'] = '淘金新手';
        } elseif (in_array($level, [UserRightNew::USER_LEVEL4, UserRightNew::USER_LEVEL5])) {
            $aMcnUser['level'] = '淘金达人';
        } elseif (in_array($level, [UserRightNew::USER_LEVEL6, UserRightNew::USER_LEVEL7])) {
            $aMcnUser['level'] = '淘金专家';
        } else {
            $aMcnUser['level'] = '等级较低';
        }

//        // 修改商业等级
//        if ($aMcnUser['creator_level'] == GrowthConfig::LEVEL_3) {
//            $aMcnUser['level'] = '淘金新手';
//        } elseif (in_array($aMcnUser['creator_level'], [GrowthConfig::LEVEL_4, GrowthConfig::LEVEL_5])) {
//            $aMcnUser['level'] = '淘金达人';
//        } elseif (in_array($aMcnUser['creator_level'], [GrowthConfig::LEVEL_6, GrowthConfig::LEVEL_7])) {
//            $aMcnUser['level'] = '淘金专家';
//        } else {
//            $aMcnUser['level'] = '等级较低';
//        }

        $content->view('mcnUser::userdetail-mcn', [
            'aUser' => $aUser,
            'aMcnUser' => $aMcnUser,
            'aMcnUserExt' => $aMcnUserExt,
            'aProfession' => $aProfession,
            'aProfessionAll' => $aProfessionAll,
            'aFamilyStructure' => ['独居人士', '二人世界', '有娃夫妻', '三世同堂', '多元家庭'],
            'aPersonalPreference' => ['享受陪伴的爱宠一族', '经验丰富的装修能手', '聪明能干的家务爱好者', '会买会用的种草达人', '审美一流的搭配能手', '先锋理性的测评达人', '热爱自然的绿植达人', '品味独特的收藏爱好者', '讲究吃喝的美食爱好者', '教育有方的亲子家长'],
            'sStartTime' => '2010-01-01 00:00:00',
            'sEndTime' => date('Y-m-d H:i:s'),
        ]);
        return $content;
    }
}
